<template>
  <div class="citySelect block">
    <el-cascader
      :popper-class="popperClass"
      placeholder="请点击选择城市"
      :size="size"
      :options="options"
      :props="props"
      collapse-tags
      v-model="selectedOptions"
      @change="handleChange"
      clearable
      filterable
    ></el-cascader>
  </div>
</template>

<script>
export default {
  name: 'CitySelect',
  created() {
    this.initDistPicker();
  },

  props: {
    popperClass: {
      type: String,
      default: ''
    },
    size: {
      type: String,
      default: 'mini'
    },
    level: {
      type: [String, Number],
      default: 1
    },
    value: {
      type: [Array, Object],
      default: () => []
    },
    props: {
      type: Object,
      default: () => {}
    }
  },
  methods: {
    initDistPicker() {
      let self = this;
      let distData = require('./districts.json');
      let options = [];
      // 省
      for (var provinceKy in distData['100000']) {
        let optProvinceItem = {
          value: provinceKy,
          label: distData['100000'][provinceKy]
        };
        if (distData[provinceKy] && this.level > 1) {
          // 市
          for (var cityKy in distData[provinceKy]) {
            optProvinceItem.children = optProvinceItem.children ? optProvinceItem.children : [];
            let optCityItem = {
              value: cityKy,
              label: distData[provinceKy][cityKy]
            };
            if (distData[cityKy] && this.level > 2) {
              // 区
              for (var areaKy in distData[cityKy]) {
                optCityItem.children = optCityItem.children ? optCityItem.children : [];
                let optAreaItem = {
                  value: areaKy,
                  label: distData[cityKy][areaKy]
                };
                optCityItem.children.push(optAreaItem);
              }
            }
            optProvinceItem.children.push(optCityItem);
          }
        }
        options.push(optProvinceItem);
      }
      self.distData = distData;
      self.options = options;
      self.selectedOptions = self.value;
      // console.log('selectedOptions', self.selectedOptions)
    },
    //选择地区
    handleChange(value) {
      let self = this,
        selectedCitys = [],
        selectedCitysParents = [],
        selectedProvinceIds = {};

      if (this.props && this.props.multiple) {
        this.selectedOptions.forEach(item => {
          selectedProvinceIds[item[0]] ? selectedProvinceIds[item[0]].push(item) : (selectedProvinceIds[item[0]] = [item]);
        });
      }

      //获取省名
      self.options.forEach((item, index) => {
        if (item.value == value[0]) {
          self.cityArr = item.children; //存储城市列表
          self.province = item.label;
          self.pIndex = item.value;
        }
        if (selectedProvinceIds[item.value]) {
          this.level === 1 &&
            selectedCitys.push({
              label: item.label,
              name: item.label,
              code: item.value
            });

          if (index === 0 && this.level === 1) {
            selectedCitysParents.push({
              label: item.label,
              name: item.label,
              code: item.value
            });
          }

          if (this.level > 1) {
            let citys = item.children,
              selectedCityIds = [];

            selectedProvinceIds[item.value].forEach(province => {
              selectedCityIds[province[1]] ? selectedCityIds[province[1]].push(province) : (selectedCityIds[province[1]] = [province]);
            });
            citys &&
              citys.forEach((city, city_index) => {
                if (selectedCityIds[city.value]) {
                  if (this.level === 2 && city.children) {
                    selectedCitys.push({
                      label: item.label + ' ' + city.label,
                      name: city.label,
                      code: city.value
                    });
                    city_index == 0 &&
                      selectedCitysParents.push({
                        label: item.label,
                        name: item.label,
                        code: item.value
                      });
                  }
                  if (this.level > 2 && city.children) {
                    let areas = city.children,
                      selectedAreaIds = [];
                    selectedCityIds[city.value].forEach(city => {
                      selectedAreaIds[city[2]] ? selectedAreaIds[city[2]].push(city) : (selectedAreaIds[city[2]] = [city]);
                    });
                    areas &&
                      areas.forEach((area, area_index) => {
                        if (selectedAreaIds[area.value]) {
                          selectedCitys.push({
                            label: item.label + ' ' + city.label + ' ' + area.label,
                            name: area.label,
                            code: area.value
                          });
                          area_index === 0 &&
                            selectedCitysParents.push({
                              label: item.label + ' ' + city.label,
                              name: city.label,
                              code: city.value
                            });
                        }
                      });
                  }
                }
              });
          }
        }
      });
      //获取市名
      if (this.level > 1) {
        self.cityArr.forEach((item, index) => {
          if (item.value == value[1]) {
            self.areaArr = item.children; //存储区县列表
            self.city = item.label;
            self.pIndex = item.value;
          }
        });
      }

      //获取区县名
      if (this.level > 2) {
        self.areaArr.forEach((item, index) => {
          if (item.value == value[2]) {
            self.area = item.label;
            self.pIndex = item.value;
          }
        });
      }
      self.provinceCityArea = self.province + self.city + self.area;
      let result = {
        province: self.province,
        city: self.city,
        area: self.area,
        provinceCityArea: self.provinceCityArea,
        pIndex: self.pIndex,
        selectedCitysParents: selectedCitysParents,
        selectedCitys: selectedCitys
      };

      this.$emit('input', this.selectedOptions);
      this.$emit('change', result);
    }
  },
  watch: {
    level(newVal, oldVal) {
      this.initDistPicker();
    },
    value(newVal, oldVal) {
      this.selectedOptions = newVal;
    }
  },
  data() {
    return {
      options: [],
      selectedOptions: [],
      cityArr: [], //城市列表
      areaArr: [], //区县列表
      province: '', //省
      city: '', //市
      area: '', // 区县,
      provinceCityArea: '', //选择器选择的省市区,
      pIndex: '' //区域代码
    };
  }
};
</script>

<style scoped lang="scss"></style>
